<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="78%">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading">
      <!-- 基本信息 -->
      <el-card class="box-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="维修单号">
              <span>{{ jobDetail.code || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="故障分类">
              <span>{{ jobDetail.faultName || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="模具编码">
              <span>{{ jobDetail.accountCode || '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="故障时间">
              <span>{{ accountDetail.faultTime ? formatDate(accountDetail.faultTime) : '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="申请人">
              <span>{{ jobDetail.applicantName || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="紧急程度">
              <dict-tag :type="DICT_TYPE.MOLD_REPAIR_URGENCY_LEVEL" :value="accountDetail.urgencyLevel" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="所属部门">
              <span>{{ jobDetail.departName || '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="故障描述">
              <div class="rich-text-content" v-html="accountDetail.faultDescription || '-'"></div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>

      <!-- 报工信息 -->
      <el-card class="box-card mt-20" shadow="never">
        <template #header>
          <div class="card-header">
            <span>报工信息</span>
          </div>
        </template>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="维修分类">
              <span>{{ jobDetail.repairCategoryName || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="维修人员">
              <span>{{ formatRepairers(jobDetail.repairerIds) || '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务接收时间">
              <span>{{ jobDetail.jobReceiveTime ? formatDate(jobDetail.jobReceiveTime) : '-' }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="任务开始时间">
              <span>{{ jobDetail.jobStartTime ? formatDate(jobDetail.jobStartTime) : '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="任务结束时间">
              <span>{{ jobDetail.jobEndTime ? formatDate(jobDetail.jobEndTime) : '-' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="理论维修工时">
              <span>{{ jobDetail.jobExecutionDuration || '-' }} 分钟</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="实际开始时间" prop="actualStartTime">
              <el-date-picker v-model="formData.actualStartTime" type="datetime" placeholder="选择实际开始时间" value-format="x"
                format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际结束时间" prop="actualEndTime">
              <el-date-picker v-model="formData.actualEndTime" type="datetime" placeholder="选择实际结束时间" value-format="x"
                format="YYYY-MM-DD HH:mm:ss" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="实际维修工时">
              <span>{{ calculateActualDuration() }} 分钟</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="维修成本">
              <el-input-number v-model="formData.repairCost" :min="0" :precision="2" placeholder="请输入维修成本" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="故障分析">
              <el-input v-model="formData.faultAnalysis" type="textarea" :rows="3" placeholder="请输入故障分析" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="维修项目">
              <el-input v-model="formData.repairItems" type="textarea" :rows="3" placeholder="请输入维修项目" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button @click="handleCancelWorkReport" type="warning">撤销报工</el-button>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">审 核</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { RepairAccountApi } from '@/api/mold/repairaccount'
import { RepairJobApi, RepairJobModStatus } from '@/api/mold/repairjob'
import * as UserApi from '@/api/system/user'
import type { UserVO } from '@/api/system/user'
import { DICT_TYPE } from '@/utils/dict'
import { dayjs } from 'element-plus'
import { bool } from 'vue-types'

const dialogTitle = ref('审核')
const dialogVisible = ref(false)
const formLoading = ref(false)
const accountDetail = ref({}) // 存储account详情
const jobDetail = ref({}) // 存储job详情
const formRef = ref() // 表单引用

// 表单验证规则
const formRules = {
  actualStartTime: [
    { required: true, message: '实际开始时间不能为空', trigger: 'change' }
  ],
  actualEndTime: [
    { required: true, message: '实际结束时间不能为空', trigger: 'change' }
  ]
}

const formData = ref({
  id: undefined, // job ID
  repairCategoryId: undefined, // 维修分类ID
  repairerIds: [], // 维修人员IDs
  actualStartTime: undefined, // 实际开始时间
  actualEndTime: undefined, // 实际结束时间
  actualExecutionDuration: undefined, // 实际维修工时
  repairCost: undefined, // 维修成本
  faultAnalysis: '', // 故障分析
  repairItems: '' // 维修项目
})

const message = useMessage() // 消息弹窗
const userList = ref<UserVO[]>([]) // 用户列表

/** 打开弹窗 */
const open = async (id: number, jobId: number) => {
  dialogVisible.value = true
  dialogTitle.value = '审核'

  // 重置表单
  formData.value = {
    id: undefined,
    repairCategoryId: undefined,
    repairerIds: [],
    actualStartTime: undefined,
    actualEndTime: undefined,
    actualExecutionDuration: undefined,
    repairCost: undefined,
    faultAnalysis: '',
    repairItems: ''
  }

  await Promise.all([
    getRepairAccount(id),
    getRepairJob(jobId),
    getUserList()
  ])
}

// 暴露方法给父组件使用
defineExpose({ open })

/** 获取维修单详情 */
const getRepairAccount = async (id: number) => {
  try {
    const data = await RepairAccountApi.getRepairAccount(id)
    formData.value.id = data.id // 设置维修单ID
    accountDetail.value = data
  } catch (error) {
    message.error('获取审核信息失败')
    console.error(error)
  }
}

/** 获取维修任务详情 */
const getRepairJob = async (id: number) => {
  try {
    const data = await RepairJobApi.getRepairJob(id)
    jobDetail.value = data

    // 填充表单数据
    formData.value = {
      id: data.id,
      repairCategoryId: data.repairCategoryId,
      repairerIds: data.repairerIds || [],
      actualStartTime: data.actualStartTime,
      actualEndTime: data.actualEndTime,
      actualExecutionDuration: data.actualExecutionDuration,
      repairCost: data.repairCost,
      faultAnalysis: data.faultAnalysis || '',
      repairItems: data.repairItems || ''
    }
  } catch (error) {
    message.error('获取审核信息失败')
    console.error(error)
  }
}

/** 获取用户列表 */
const getUserList = async () => {
  try {
    userList.value = await UserApi.getSimpleUserList()
  } catch (error) {
    message.error('获取用户列表失败')
    console.error(error)
  }
}

/** 格式化维修人员显示 */
const formatRepairers = (repairerIds: number[]) => {
  if (!repairerIds || !userList.value.length) return '-'

  return repairerIds.map(id => {
    const user = userList.value.find(user => user.id === id)
    return user ? user.nickname : `未知用户(${id})`
  }).join('、')
}



/** 计算实际维修工时（以分钟为单位） */
const calculateActualDuration = () => {
  const start = formData.value.actualStartTime
  const end = formData.value.actualEndTime

  if (!start || !end) {
    formData.value.actualExecutionDuration = undefined
    return '-'
  }

  // 确保结束时间晚于开始时间
  if (end <= start) {
    formData.value.actualExecutionDuration = 0
    return '0'
  }

  // 计算分钟数
  const duration = (end - start) / (1000 * 60)
  const roundedDuration = Math.round(duration)
  formData.value.actualExecutionDuration = roundedDuration
  return roundedDuration
}


/** 撤销报工 */
const handleCancelWorkReport = async () => {
  if (!formData.value.id) {
    message.error('无效的任务ID')
    return
  }

  const repairJobModStatus: RepairJobModStatus = {
    id: formData.value.id,
    status: 3 // 设置状态为“维修中”,
  }
  var f = await RepairJobApi.modStatus(repairJobModStatus)

  if (!f) {
    message.error('撤销报工失败')
    return
  }

  message.success('撤销成功')
  dialogVisible.value = false

  // 触发成功事件，让父组件刷新列表
  emit('success')
}

/** 提交表单 */
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid: boolean) => {
    if (!valid) return

    // 验证时间逻辑
    const start = formData.value.actualStartTime
    const end = formData.value.actualEndTime

    if (end <= start) {
      message.error('实际结束时间必须晚于实际开始时间')
      return
    }

    // 提交审核
    await submitAudit()
  })
}

/** 提交审核 */
const submitAudit = async () => {
  try {
    formLoading.value = true
    // 调用审核接口
    await RepairAccountApi.auditRepairAccount(formData.value)
    message.success('审核成功')
    dialogVisible.value = false
    // 触发成功事件，让父组件刷新列表
    emit('success')
  } catch (error) {
    message.error('审核失败')
    console.error(error)
  } finally {
    formLoading.value = false
  }
}

/** 格式化时间戳 */
const formatDate = (timestamp: number | string | Date) => {
  if (!timestamp) return '-'
  // 如果是字符串或数字形式的时间戳，转换为数字
  const ts = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp
  return dayjs(ts).format('YYYY-MM-DD HH:mm:ss')
}

// 定义事件
const emit = defineEmits(['success'])

// 监听时间变化，自动计算工时
watch([() => formData.value.actualStartTime, () => formData.value.actualEndTime], () => {
  calculateActualDuration()
})
</script>

<style scoped>
.mt-20 {
  margin-top: 20px;
}

.rich-text-content {
  line-height: 1.6;
}
</style>